package com.bachelor.community.controller;

import cn.hutool.core.util.ObjectUtil;
import com.bachelor.community.annotation.UnInterception;
import com.bachelor.community.model.dto.QuestionDTO;
import com.bachelor.community.model.entity.*;
import com.bachelor.community.model.vo.QuestionVO;
import com.bachelor.community.service.intf.*;
import com.bachelor.community.utils.Result;
import com.bachelor.community.utils.UserSupport;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/questions")
public class QuestionController {

    private final QuestionService questionService;
    private final UserService userService;
    private final QuestionTagService questionTagService;
    private final AnswerService answerService;
    private final CommentService commentService;
    private final UserSupport userSupport;

    @Autowired
    public QuestionController(QuestionService questionService, UserService userService, QuestionTagService questionTagService, AnswerService answerService, CommentService commentService, UserSupport userSupport) {
        this.questionService = questionService;
        this.userService = userService;
        this.questionTagService = questionTagService;
        this.answerService = answerService;
        this.commentService = commentService;
        this.userSupport = userSupport;
    }

    @PostMapping
    public Result insertQuestion(@RequestBody QuestionDTO questionDTO) {
        Integer creator = userSupport.getCurrentUserId();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", creator);
        User user = userService.getOne(queryWrapper);
        return Result.succeed("201", questionService.insertQuestion(questionDTO, user));
    }

    @GetMapping
    @UnInterception
    public Result listQuestions(@RequestParam("offset") int currentPage,
                                @RequestParam("limit") int pageSize,
                                @RequestParam(value = "order", defaultValue = "latest", required = false) String orderColumn,
                                @RequestParam(value = "keyword", required = false) String keyword,
                                @RequestParam(value = "state", required = false) Integer state,
                                @RequestParam(value = "userId", required = false) Integer userId) {
        if (ObjectUtil.isEmpty(keyword) && !ObjectUtil.isEmpty(userId)) {
            return Result.succeed("200", questionService.listQuestionsByUserId(currentPage, pageSize, userId));
        } else if (state != null) {
            QueryWrapper<QuestionVO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("state", state);
            if (orderColumn.equalsIgnoreCase("earliest")) {
                queryWrapper.orderByAsc("create_time");
            } else {
                queryWrapper.orderByDesc("create_time");
            }
            return Result.succeed("200", questionService.listQuestions(currentPage, pageSize, queryWrapper));
        } else {
            return Result.succeed("200", questionService.listQuestions(currentPage, pageSize, orderColumn, keyword));
        }
    }

    @GetMapping("/tags/{tagId}")
    @UnInterception
    public Result listQuestionsByTagId(@RequestParam("offset") int currentPage,
                                       @RequestParam("limit") int pageSize,
                                       @PathVariable Integer tagId,
                                       @RequestParam(value = "tab", defaultValue = "latest") String tabName) {
        return Result.succeed("200", questionService.listQuestionsByTagId(currentPage, pageSize, tagId, tabName));
    }

    @GetMapping(value = "/{questionId}")
    @UnInterception
    public Result getQuestion(@PathVariable("questionId") Long id) {
        return Result.succeed("200", questionService.getQuestionVOById(id));
    }

    @PatchMapping("{questionId}")
    public Result partialUpdateQuestion(@PathVariable("questionId") Long id, @RequestBody QuestionDTO questionDTO) {
        return Result.succeed("200", questionService.partialUpdateQuestion(id, questionDTO));
    }

    @PatchMapping
    public Result partialUpdateBatchQuestion(@RequestBody List<Integer> questionIds) {
        List<Question> questionList = questionService.listByIds(questionIds);
        questionList.forEach(question -> {
            question.setState(1);
        });
        return Result.succeed("200", questionService.updateBatchById(questionList));
    }

    @DeleteMapping("{questionId}")
    public Result deleteQuestion(@PathVariable("questionId") Long id) {
        QueryWrapper<QuestionTagRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", id);
        QueryWrapper<Answer> answerQueryWrapper = new QueryWrapper<>();
        answerQueryWrapper.eq("question_id", id);
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("question_id", id);
        if (questionTagService.remove(queryWrapper) &&
                answerService.remove(answerQueryWrapper) &&
                commentService.remove(commentQueryWrapper)) {
            return Result.succeed("204", questionService.removeById(id));
        } else {
            return Result.fail("500", "服务器故障！");
        }
    }
}
